package com.shopping.admin.Intercepter;

import com.shopping.common.core.constant.GloatDeletedFlagEnum;
import com.shopping.common.core.object.TokenData;
import com.shopping.common.sp.model.log.Log;
import com.shopping.service.service.log.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 日志拦截器
 * @author: zlw
 * @date: 2024/9/18
 */
@Component
public class LogInterceptercepter extends HandlerInterceptorAdapter {

    @Autowired
    private LogService logService;

    /**
     * 记录开始时间
     */
    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-StartTime");

    private Logger logger = LoggerFactory.getLogger(LogInterceptercepter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        long startTime = System.currentTimeMillis();
        startTimeThreadLocal.set(startTime);
        //记录日志
        //请求路径记录
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/user/login")){
            return true;
        }
        System.out.println("请求的相对路径是: {} " + requestURI);
        String contextPath = request.getContextPath();
        System.out.println("请求的上下文路径是 {} " + contextPath);
        //获取当前登录用户
        Long currentLoginUserId = TokenData.takeFormRequest().getUserId();
        String currentLoginUserName = TokenData.takeFormRequest().getUserName();
        Log log = new Log();
        log.setLogUrl(requestURI);
        log.setUserId(currentLoginUserId);
        log.setUserName(currentLoginUserName);
        log.setCreateUserId(currentLoginUserId);
        log.setCreateUserName(currentLoginUserName);
        log.setCreateTime(new Date());
        log.setUpdateUserId(currentLoginUserId);
        log.setUpdateUserName(currentLoginUserName);
        log.setUpdateTime(new Date());
        Integer deletedFlag = GloatDeletedFlagEnum.GLOAT_DELETED_FLAG.getDeletedFlag();
        log.setDeletedFlag(deletedFlag);

        logService.save(log);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //生成视图前,处理数据后生效
        System.out.println("生成视图前,处理数据后");
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求处理后调用,多用于清理资源");
        //计算请求完成时间
        long endTime = System.currentTimeMillis();
        Long beginTime = startTimeThreadLocal.get();
        long consumeTime  = endTime - beginTime;

        if(consumeTime > 500) {//此处认为处理时间超过500毫秒的请求为慢请求
            //TODO 记录到日志文件
            logger.info(String.format("%s consume %d millis", request.getRequestURI(), consumeTime));
        }
        System.out.println("System版: 请求所花费时间:" + consumeTime / 1000 + "s");
        logger.info("logger版: 请求所花费时间: {} ms",consumeTime );
        logger.info("logger版: 请求所花费时间: {} s", consumeTime / 1000);
    }
}
